package edu.nf.vrs.admin.interceptor;

import edu.nf.vrs.admin.commons.Const;
import org.nf.vrs.userservice.dto.UserDTO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Lv
 * @date 2022/4/2
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDTO user = (UserDTO) request.getSession().getAttribute("user");
        if (user == null){
            //跳出iframe转向登录页面
            response.getWriter().println("<script>window.parent.localtion.href='/admin/login.html'</script>");
            return false;
        }
        if (user.getRole() != null){
            if (!Const.SUPER_ADMIN.equals(user.getRole().getRoleName())){
                response.setContentType("text/plain;charset=utf-8");
                response.getWriter().println("您的账号未授权，请联系管理员！");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
